<template>
  <el-cascader v-bind="$attrs" :value="selectValue" :options="dataSource" :props="props"
               @change="activeChange">
  </el-cascader>
</template>

<script>
  import Api from '@/util/api'
  import DataModel from 'framework/datamodel';

  export default {
    name: "ElCascaderDistrict",
    data() {
      return {
        selectValue: [],
        dataSource: [],
        dataSourceHash: {},
        props: {
          label: 'name',
          value: 'guid',
          children: 'children'
        },
      }
    },
    props: ['value'],
    async mounted() {

      const dataSet = await Api.host('static').get('/areas.json');
      this.dataSource = dataSet.data;
      this.selectValue = this.getAreasItemGuid(this.value);

    },
    methods: {
      getAreasItem(guid, dataSource) {
        for (let indexArea = 0; indexArea < dataSource.length; indexArea++) {
          let path = [];
          let item = dataSource[indexArea];
          if (item.guid === guid) {
            path.push(item);
            return path;
          }
          if (item.hasOwnProperty('children')) {
            let subItem = this.getAreasItem(guid, item['children']);
            if (subItem.length > 0) {
              path.push(item);
              path = path.concat(subItem);
              return path
            }
          }
        }
        return [];
      },
      getAreasItemGuid(guid) {
        const guids = [];
        for (let item of this.getAreasItem(guid, this.dataSource)) {
          guids.push(item.guid);
        }
        return guids;
      },
      async activeChange(values) {

        let value = null;
        if (values.length > 0) {
          value = values[values.length - 1];
        }
        this.$emit('input', value);
      }
    }
  }
</script>

<style scoped>

</style>
